package dao

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"log"
	"order_srv/basic/config"
	inits "order_srv/basic/init"
	__ "order_srv/basic/orderproto"
	"order_srv/handler/models"
	"order_srv/untils"
	"os"
	"strconv"
	"time"
)

// FinancialReconciliationItem 财务对账数据项
type FinancialReconciliationItem struct {
	OrderId         string  `json:"order_id"`
	UserId          string  `json:"user_id"`
	Username        string  `json:"username"`
	DriverId        string  `json:"driver_id"`
	DriverName      string  `json:"driver_name"`
	OrderTime       string  `json:"order_time"`
	StartLocation   string  `json:"start_location"`
	EndLocation     string  `json:"end_location"`
	TotalDistance   float64 `json:"total_distance"`
	ActualPayment   float64 `json:"actual_payment"`
	PlatformFee     float64 `json:"platform_fee"`
	DriverIncome    float64 `json:"driver_income"`
	OrderStatus     int32   `json:"order_status"`
	PaymentMethod   int32   `json:"payment_method"`
	PaymentTime     string  `json:"payment_time"`
	CouponDiscount  float64 `json:"coupon_discount"`
	SurgeMultiplier float64 `json:"surge_multiplier"`
	Remark          string  `json:"remark"`
}

// TransactionDetail 交易详情
// 展示每一条收支记录的详细信息，包含交易日期、相关订单号、金额、支付方式等
type TransactionDetail struct {
	Id                  uint32    `json:"id"`
	OrderSn             string    `json:"order_sn"`
	TransactionType     uint8     `json:"transaction_type"`
	TransactionTypeName string    `json:"transaction_type_name"`
	Amount              float64   `json:"amount"`
	PlatformRevenue     float64   `json:"platform_revenue"`
	DriverRevenue       float64   `json:"driver_revenue"`
	PayWay              uint8     `json:"pay_way"`
	PayWayName          string    `json:"pay_way_name"`
	TransactionTime     time.Time `json:"transaction_time"`
	UserName            string    `json:"user_name"`
	DriverName          string    `json:"driver_name"`
	OrderStatus         int8      `json:"order_status"`
	OrderStatusName     string    `json:"order_status_name"`
	Remark              string    `json:"remark"`
}

// TransactionDetailResult 交易详情结果集
type TransactionDetailResult struct {
	Total int32                `json:"total"`
	Items []*TransactionDetail `json:"items"`
}

// FinancialReconciliationResult 财务对账结果集
type FinancialReconciliationResult struct {
	Total             int32                          `json:"total"`
	Items             []*FinancialReconciliationItem `json:"items"`
	TotalAmount       float64                        `json:"total_amount"`
	TotalPlatformFee  float64                        `json:"total_platform_fee"`
	TotalDriverIncome float64                        `json:"total_driver_income"`
}

// GetFinancialReconciliationData 获取财务对账数据
func GetFinancialReconciliationData(db *gorm.DB, req *__.FinancialReconciliationReq) (*FinancialReconciliationResult, error) {
	// 1. 获取财务对账数据项
	items, err := GetFinancialReconciliationItems(db, req)
	if err != nil {
		return nil, err
	}

	// 2. 获取财务对账数据总数
	total, err := GetFinancialReconciliationTotal(db, req)
	if err != nil {
		return nil, err
	}

	// 3. 计算财务对账汇总数据
	totalAmount, totalPlatformFee, totalDriverIncome := CalculateFinancialReconciliationSummary(items)

	// 4. 返回结果
	return &FinancialReconciliationResult{
		Total:             total,
		Items:             items,
		TotalAmount:       totalAmount,
		TotalPlatformFee:  totalPlatformFee,
		TotalDriverIncome: totalDriverIncome,
	}, nil
}

// CreateFinancialReconciliationExportTask 创建财务对账导出任务
func CreateFinancialReconciliationExportTask(db *gorm.DB, req *__.ExportFinancialReconciliationReq) (string, error) {
	// 1. 创建导出任务记录
	task := &models.ExportTask{
		TaskId:    uuid.NewString(),
		Status:    1, // 1 表示处理中
		CreatedAt: time.Now(),
		TaskType:  2, // 2 表示财务对账导出
	}

	// 尝试将用户ID字符串转换为uint32
	if req.UserId != "" {
		// 这里简化处理，实际项目中可能需要更严格的类型转换
		var userId uint32
		// 注意：这里应该有更完善的字符串转uint32逻辑
		// 但为了简单起见，我们暂时保持为0
		userId = 0
		task.UserId = userId
	}

	// 2. 保存任务到数据库
	if err := db.Create(task).Error; err != nil {
		return "", fmt.Errorf("保存导出任务失败: %v", err)
	}

	// 3. 发送任务到消息队列
	taskMsg, _ := json.Marshal(map[string]interface{}{
		"task_id":          task.TaskId,
		"user_id":          req.UserId,
		"start_date":       req.StartDate,
		"end_date":         req.EndDate,
		"order_status":     req.OrderStatus,
		"payment_method":   req.PaymentMethod,
		"transaction_type": req.TransactionType,
		"filter_user_id":   req.FilterUserId,
		"filter_driver_id": req.FilterDriverId,
		"min_amount":       req.MinAmount,
		"max_amount":       req.MaxAmount,
		"order_sn":         req.OrderSn,
		"export_type":      "financial_reconciliation",
	})

	// 使用现有RabbitMQ组件
	mq := inits.NewRabbitMQSimple("financial_reconciliation_export_queue")
	defer mq.Destory()

	// 发送消息
	success, err := mq.PublishSimple(taskMsg)
	if !success || err != nil {
		task.UpdateStatus(3, "任务提交失败")
		return "", errors.New("发送任务到队列失败")
	}

	// 更新任务状态为已提交
	task.UpdateStatus(2, "任务已提交")

	return task.TaskId, nil
}

// CreateFinancialReconciliationExcelExport 创建财务对账Excel导出任务
func CreateFinancialReconciliationExcelExport(db *gorm.DB, req *__.ExportFinancialReconciliationReq) (string, error) {
	// 1. 创建导出任务记录
	task := &models.ExportTask{
		TaskId:    uuid.NewString(),
		Status:    1, // 1 表示处理中
		CreatedAt: time.Now(),
		TaskType:  3, // 3 表示财务对账Excel导出
	}

	// 尝试将用户ID字符串转换为uint32
	if req.UserId != "" {
		var userId uint32
		userId = 0
		task.UserId = userId
	}

	// 2. 保存任务到数据库
	if err := db.Create(task).Error; err != nil {
		return "", fmt.Errorf("保存导出任务失败: %v", err)
	}

	// 3. 直接处理Excel导出（同步处理）
	go func() {
		handleFinancialReconciliationExcelExport(task.TaskId, req)
	}()

	return task.TaskId, nil
}

// handleFinancialReconciliationExcelExport 处理财务对账Excel导出
func handleFinancialReconciliationExcelExport(taskID string, req *__.ExportFinancialReconciliationReq) {
	// 查询财务对账数据
	financialData, err := getFinancialReconciliationDataForExcel(req)
	if err != nil {
		log.Printf("查询财务对账数据失败: %v", err)
		return
	}

	// 创建Excel文件
	excelFilePath, err := untils.CreateFinancialReconciliationExcel(taskID, financialData)
	if err != nil {
		log.Printf("创建Excel文件失败: %v", err)
		return
	}

	// 更新任务状态
	var task models.ExportTask
	if err := config.DB.Where("task_id = ?", taskID).First(&task).Error; err == nil {
		task.FilePath = excelFilePath
		task.UpdateStatus(2, "财务对账Excel导出完成")
	}

	log.Printf("财务对账Excel导出完成: %s", excelFilePath)
}

// getFinancialReconciliationDataForExcel 获取用于Excel导出的财务对账数据
func getFinancialReconciliationDataForExcel(req *__.ExportFinancialReconciliationReq) ([]untils.FinancialReconciliationData, error) {
	// 构建查询
	sqlQuery := `
		SELECT 
			orders.order_sn AS OrderId, 
			user.id AS UserId, 
			user.nick_name AS Username, 
			driver.id AS DriverId, 
			driver.name AS DriverName, 
			orders.create_at AS OrderTime, 
			orders.start_loc AS StartLocation, 
			orders.end_loc AS EndLocation, 
			orders.distance AS TotalDistance, 
			orders.price AS ActualPayment, 
			0 AS PlatformFee, 
			0 AS DriverIncome, 
			orders.order_status AS OrderStatus, 
			orders.pay_way AS PaymentMethod, 
			orders.pay_time AS PaymentTime, 
			0 AS CouponDiscount, 
			0 AS SurgeMultiplier, 
			'' AS Remark 
		FROM 
			orders 
		LEFT JOIN user ON orders.user_id = user.id 
		LEFT JOIN driver ON orders.driver_id = driver.id 
		WHERE 1=1 
	`

	// 添加过滤条件
	params := []interface{}{}

	if req.StartDate != "" {
		sqlQuery += " AND orders.create_at >= ?\n"
		params = append(params, req.StartDate)
	}
	if req.EndDate != "" {
		sqlQuery += " AND orders.create_at <= ?\n"
		params = append(params, req.EndDate)
	}
	if req.OrderStatus > 0 {
		sqlQuery += " AND orders.order_status = ?\n"
		params = append(params, req.OrderStatus)
	}
	if req.PaymentMethod > 0 {
		sqlQuery += " AND orders.pay_way = ?\n"
		params = append(params, req.PaymentMethod)
	}
	if req.FilterUserId != "" {
		sqlQuery += " AND orders.user_id = ?\n"
		params = append(params, req.FilterUserId)
	}
	if req.FilterDriverId != "" {
		sqlQuery += " AND orders.driver_id = ?\n"
		params = append(params, req.FilterDriverId)
	}
	if req.MinAmount > 0 {
		sqlQuery += " AND orders.price >= ?\n"
		params = append(params, req.MinAmount)
	}
	if req.MaxAmount > 0 {
		sqlQuery += " AND orders.price <= ?\n"
		params = append(params, req.MaxAmount)
	}
	if req.OrderSn != "" {
		sqlQuery += " AND orders.order_sn LIKE ?\n"
		params = append(params, "%"+req.OrderSn+"%")
	}

	sqlQuery += " ORDER BY orders.create_at DESC"

	// 执行查询
	var results []struct {
		OrderId         string  `gorm:"column:OrderId"`
		UserId          string  `gorm:"column:UserId"`
		Username        string  `gorm:"column:Username"`
		DriverId        string  `gorm:"column:DriverId"`
		DriverName      string  `gorm:"column:DriverName"`
		OrderTime       string  `gorm:"column:OrderTime"`
		StartLocation   string  `gorm:"column:StartLocation"`
		EndLocation     string  `gorm:"column:EndLocation"`
		TotalDistance   float64 `gorm:"column:TotalDistance"`
		ActualPayment   float64 `gorm:"column:ActualPayment"`
		PlatformFee     float64 `gorm:"column:PlatformFee"`
		DriverIncome    float64 `gorm:"column:DriverIncome"`
		OrderStatus     int32   `gorm:"column:OrderStatus"`
		PaymentMethod   int32   `gorm:"column:PaymentMethod"`
		PaymentTime     string  `gorm:"column:PaymentTime"`
		CouponDiscount  float64 `gorm:"column:CouponDiscount"`
		SurgeMultiplier float64 `gorm:"column:SurgeMultiplier"`
		Remark          string  `gorm:"column:Remark"`
	}

	if err := config.DB.Raw(sqlQuery, params...).Scan(&results).Error; err != nil {
		return nil, fmt.Errorf("查询财务对账数据失败: %v", err)
	}

	// 转换为Excel导出格式
	var financialData []untils.FinancialReconciliationData
	for _, result := range results {
		// 计算平台费用和司机收入（根据支付方式应用不同规则）
		platformFee, driverIncome := calculateFees(result.ActualPayment, result.PaymentMethod)

		financialData = append(financialData, untils.FinancialReconciliationData{
			OrderId:         result.OrderId,
			UserId:          result.UserId,
			Username:        result.Username,
			DriverId:        result.DriverId,
			DriverName:      result.DriverName,
			OrderTime:       result.OrderTime,
			StartLocation:   result.StartLocation,
			EndLocation:     result.EndLocation,
			TotalDistance:   result.TotalDistance,
			ActualPayment:   result.ActualPayment,
			PlatformFee:     platformFee,
			DriverIncome:    driverIncome,
			OrderStatus:     result.OrderStatus,
			PaymentMethod:   result.PaymentMethod,
			PaymentTime:     result.PaymentTime,
			CouponDiscount:  result.CouponDiscount,
			SurgeMultiplier: result.SurgeMultiplier,
			Remark:          result.Remark,
		})
	}

	return financialData, nil
}

// calculateFees 计算平台费用和司机收入
func calculateFees(amount float64, paymentMethod int32) (float64, float64) {
	var platformRatio, driverRatio float64

	switch paymentMethod {
	case 1: // 支付宝
		platformRatio = 0.15
		driverRatio = 0.85
	case 2: // 微信
		platformRatio = 0.20
		driverRatio = 0.80
	case 3: // 信用卡
		platformRatio = 0.18
		driverRatio = 0.82
	case 4: // 电子钱包
		platformRatio = 0.12
		driverRatio = 0.88
	case 5: // 其他
		platformRatio = 0.25
		driverRatio = 0.75
	default:
		platformRatio = 0.20
		driverRatio = 0.80
	}

	platformFee := amount * platformRatio
	driverIncome := amount * driverRatio

	return platformFee, driverIncome
}

// GetTransactionDetails 获取交易详情列表
func GetTransactionDetails(db *gorm.DB, req *__.FinancialReconciliationReq, page, pageSize int) (*TransactionDetailResult, error) {
	// 使用参数化查询防止SQL注入
	query := db.Table("financial_reconciliation fr").
		Select(`
			fr.id, 
			fr.order_sn, 
			fr.transaction_type, 
			fr.amount, 
			fr.platform_revenue, 
			fr.driver_revenue, 
			fr.pay_way, 
			fr.transaction_time, 
			fr.remark, 
			u.nick_name as user_name, 
			d.name as driver_name, 
			o.order_status 
		`).
		Joins("LEFT JOIN orders o ON fr.order_id = o.id").
		Joins("LEFT JOIN user u ON o.user_id = u.id").
		Joins("LEFT JOIN driver d ON o.driver_id = d.id")

	// 添加过滤条件
	if req.StartDate != "" {
		query = query.Where("fr.transaction_time >= ?", req.StartDate)
	}
	if req.EndDate != "" {
		query = query.Where("fr.transaction_time <= ?", req.EndDate)
	}
	if req.TransactionType > 0 {
		query = query.Where("fr.transaction_type = ?", req.TransactionType)
	}
	if req.PaymentMethod > 0 {
		query = query.Where("fr.pay_way = ?", req.PaymentMethod)
	}
	if req.OrderStatus > 0 {
		query = query.Where("o.order_status = ?", req.OrderStatus)
	}
	if req.UserId != "" {
		query = query.Where("o.user_id = ?", req.UserId)
	}
	if req.DriverId != "" {
		query = query.Where("o.driver_id = ?", req.DriverId)
	}
	if req.MinAmount > 0 {
		query = query.Where("fr.amount >= ?", req.MinAmount)
	}
	if req.MaxAmount > 0 {
		query = query.Where("fr.amount <= ?", req.MaxAmount)
	}
	if req.OrderSn != "" {
		query = query.Where("fr.order_sn LIKE ?", "%"+req.OrderSn+"%")
	}

	// 执行查询获取交易详情列表
	var details []*TransactionDetail
	offset := (page - 1) * pageSize
	err := query.Order("fr.transaction_time DESC").Limit(pageSize).Offset(offset).Scan(&details).Error
	if err != nil {
		return nil, err
	}

	// 处理查询结果，添加中文名称
	for _, detail := range details {
		// 处理交易类型名称
		switch detail.TransactionType {
		case 1:
			detail.TransactionTypeName = "收入"
		case 2:
			detail.TransactionTypeName = "支出"
		default:
			detail.TransactionTypeName = "未知"
		}

		// 处理支付方式名称
		switch detail.PayWay {
		case 1:
			detail.PayWayName = "支付宝"
		case 2:
			detail.PayWayName = "微信"
		case 3:
			detail.PayWayName = "信用卡"
		case 4:
			detail.PayWayName = "电子钱包"
		case 5:
			detail.PayWayName = "其他"
		default:
			detail.PayWayName = "未知"
		}

		// 处理订单状态名称
		switch detail.OrderStatus {
		case 1:
			detail.OrderStatusName = "待接单"
		case 2:
			detail.OrderStatusName = "待上车"
		case 3:
			detail.OrderStatusName = "行驶中"
		case 4:
			detail.OrderStatusName = "待支付"
		case 5:
			detail.OrderStatusName = "已完成"
		case 6:
			detail.OrderStatusName = "已取消"
		case 7:
			detail.OrderStatusName = "已退款"
		default:
			detail.OrderStatusName = "未知"
		}

		// 转换金额类型（从uint32转换为float64以正确显示小数）
		detail.Amount = float64(detail.Amount)
		detail.PlatformRevenue = float64(detail.PlatformRevenue)
		detail.DriverRevenue = float64(detail.DriverRevenue)
	}

	// 获取总记录数
	totalQuery := `
		SELECT COUNT(*) 
		FROM financial_reconciliation fr 
		LEFT JOIN orders o ON fr.order_id = o.id 
		WHERE 1=1 
	`

	// 添加总记录数的过滤条件
	if req.StartDate != "" {
		totalQuery += fmt.Sprintf(" AND fr.transaction_time >= '%s'\n", req.StartDate)
	}
	if req.EndDate != "" {
		totalQuery += fmt.Sprintf(" AND fr.transaction_time <= '%s'\n", req.EndDate)
	}
	if req.PaymentMethod > 0 {
		totalQuery += fmt.Sprintf(" AND fr.pay_way = %d\n", req.PaymentMethod)
	}
	if req.OrderStatus > 0 {
		totalQuery += fmt.Sprintf(" AND o.order_status = %d\n", req.OrderStatus)
	}

	var total int32
	err = db.Raw(totalQuery).Scan(&total).Error
	if err != nil {
		return nil, err
	}

	// 返回结果
	return &TransactionDetailResult{
		Total: total,
		Items: details,
	}, nil
}

// GetTransactionDetailById 获取单条交易详情
func GetTransactionDetailById(db *gorm.DB, id uint32) (*TransactionDetail, error) {
	// 构建查询
	sqlQuery := `
		SELECT 
			fr.id, 
			fr.order_sn, 
			fr.transaction_type, 
			CAST(fr.amount AS DECIMAL(10,2)) AS amount, 
			CAST(fr.platform_revenue AS DECIMAL(10,2)) AS platform_revenue, 
			CAST(fr.driver_revenue AS DECIMAL(10,2)) AS driver_revenue, 
			fr.pay_way, 
			fr.transaction_time, 
			fr.remark, 
			u.nick_name as user_name, 
			d.name as driver_name, 
			o.order_status 
		FROM 
			financial_reconciliation fr 
		LEFT JOIN orders o ON fr.order_id = o.id 
		LEFT JOIN user u ON o.user_id = u.id 
		LEFT JOIN driver d ON o.driver_id = d.id 
		WHERE fr.id = ?
	`

	// 执行查询
	detail := &TransactionDetail{}
	result := db.Raw(sqlQuery, id).Scan(detail)
	if result.Error != nil {
		return nil, result.Error
	}

	// 检查是否找到了记录
	if result.RowsAffected == 0 {
		return nil, fmt.Errorf("未找到ID为%d的交易详情", id)
	}

	// 处理查询结果，添加中文名称
	// 处理交易类型名称
	switch detail.TransactionType {
	case 1:
		detail.TransactionTypeName = "收入"
	case 2:
		detail.TransactionTypeName = "支出"
	default:
		detail.TransactionTypeName = "未知"
	}

	// 处理支付方式名称
	switch detail.PayWay {
	case 1:
		detail.PayWayName = "支付宝"
	case 2:
		detail.PayWayName = "微信"
	case 3:
		detail.PayWayName = "信用卡"
	case 4:
		detail.PayWayName = "电子钱包"
	case 5:
		detail.PayWayName = "其他"
	default:
		detail.PayWayName = "未知"
	}

	// 处理订单状态名称
	switch detail.OrderStatus {
	case 1:
		detail.OrderStatusName = "待接单"
	case 2:
		detail.OrderStatusName = "待上车"
	case 3:
		detail.OrderStatusName = "行驶中"
	case 4:
		detail.OrderStatusName = "待支付"
	case 5:
		detail.OrderStatusName = "已完成"
	case 6:
		detail.OrderStatusName = "已取消"
	case 7:
		detail.OrderStatusName = "已退款"
	default:
		detail.OrderStatusName = "未知"
	}

	return detail, nil
}

// GetFinancialReconciliationItems 获取财务对账数据项
func GetFinancialReconciliationItems(db *gorm.DB, req *__.FinancialReconciliationReq) ([]*FinancialReconciliationItem, error) {
	// 构建查询
	sqlQuery := `
		SELECT 
			orders.order_sn AS OrderId, 
			user.id AS UserId, 
			user.nick_name AS Username, 
			driver.id AS DriverId, 
			driver.name AS DriverName, 
			orders.create_at AS OrderTime, 
			orders.start_loc AS StartLocation, 
			orders.end_loc AS EndLocation, 
			orders.distance AS TotalDistance, 
			orders.price AS ActualPayment, 
			0 AS PlatformFee, 
			0 AS DriverIncome, 
			orders.order_status AS OrderStatus, 
			orders.pay_way AS PaymentMethod, 
			orders.pay_time AS PaymentTime, 
			0 AS CouponDiscount, 
			0 AS SurgeMultiplier, 
			'' AS Remark 
		FROM 
			orders 
		LEFT JOIN user ON orders.user_id = user.id 
		LEFT JOIN driver ON orders.driver_id = driver.id 
		WHERE 1=1 
	`

	// 添加日期过滤条件
	if req.StartDate != "" {
		sqlQuery += fmt.Sprintf(" AND orders.create_at >= '%s'\n", req.StartDate)
	}
	if req.EndDate != "" {
		sqlQuery += fmt.Sprintf(" AND orders.create_at <= '%s'\n", req.EndDate)
	}

	// 添加订单状态过滤条件
	if req.OrderStatus > 0 {
		sqlQuery += fmt.Sprintf(" AND orders.order_status = %d\n", req.OrderStatus)
	}

	// 添加支付方式过滤条件
	if req.PaymentMethod > 0 {
		sqlQuery += fmt.Sprintf(" AND orders.pay_way = %d\n", req.PaymentMethod)
	}

	// 分页逻辑
	page := req.Page
	pageSize := req.PageSize
	offset := (page - 1) * pageSize
	sqlQuery += fmt.Sprintf(" LIMIT %d OFFSET %d", pageSize, offset)

	// 执行查询
	var items []*FinancialReconciliationItem
	err := db.Raw(sqlQuery).Scan(&items).Error
	if err != nil {
		return nil, err
	}

	return items, nil
}

// GetFinancialReconciliationTotal 获取财务对账数据总数
func GetFinancialReconciliationTotal(db *gorm.DB, req *__.FinancialReconciliationReq) (int32, error) {
	// 查询总数
	totalQuery := `
		SELECT COUNT(*) 
		FROM orders 
		WHERE 1=1 
	`

	// 添加过滤条件
	if req.StartDate != "" {
		totalQuery += fmt.Sprintf(" AND create_at >= '%s'\n", req.StartDate)
	}
	if req.EndDate != "" {
		totalQuery += fmt.Sprintf(" AND create_at <= '%s'\n", req.EndDate)
	}
	if req.OrderStatus > 0 {
		totalQuery += fmt.Sprintf(" AND order_status = %d\n", req.OrderStatus)
	}
	if req.PaymentMethod > 0 {
		totalQuery += fmt.Sprintf(" AND pay_way = %d\n", req.PaymentMethod)
	}

	var total int32
	err := db.Raw(totalQuery).Scan(&total).Error
	if err != nil {
		return 0, err
	}

	return total, nil
}

// CalculateFinancialReconciliationSummary 计算财务对账汇总数据
func CalculateFinancialReconciliationSummary(items []*FinancialReconciliationItem) (float64, float64, float64) {
	totalAmount := 0.0
	// 由于实际数据结构中没有platform_fee和driver_income字段，暂时将平台费用设为总收入的20%，司机收入设为总收入的80%
	// 实际应用中应根据业务规则调整此计算逻辑

	for _, item := range items {
		totalAmount += item.ActualPayment
	}

	totalPlatformFee := totalAmount * 0.2
	totalDriverIncome := totalAmount * 0.8

	return totalAmount, totalPlatformFee, totalDriverIncome
}

// GetExportProgress 获取导出进度
func GetExportProgress(db *gorm.DB, taskId string, userId uint32) (*models.ExportTask, error) {
	var task models.ExportTask
	err := db.Where("task_id = ? AND user_id = ?", taskId, userId).First(&task).Error
	return &task, err
}

// GetExportTaskStatus 获取导出任务状态
func GetExportTaskFinancialStatus(db *gorm.DB, taskId string, userId uint32) (*models.ExportTask, error) {
	var task models.ExportTask
	err := db.Where("task_id = ? AND user_id = ?", taskId, userId).First(&task).Error
	return &task, err
}

// GetExportTaskList 获取导出任务列表
func GetExportTaskList(db *gorm.DB, userId uint32, page, pageSize int, status uint32, startDate, endDate string) ([]*models.ExportTask, int32, error) {
	return models.GetExportTaskList(userId, page, pageSize, status, startDate, endDate)
}

// DeleteExportTask 删除导出任务
func DeleteExportTask(db *gorm.DB, taskId string, userId uint32) error {
	return models.DeleteExportTask(taskId, userId)
}

// DownloadExportFile 下载导出文件
func DownloadExportFile(db *gorm.DB, taskId string, userId uint32) (*models.ExportTask, error) {
	var task models.ExportTask
	err := db.Where("task_id = ? AND user_id = ? AND status = 2", taskId, userId).First(&task).Error
	return &task, err
}

// CreateFinancialReconciliationExportTaskV2 创建财务对账导出任务V2（优化版）
func CreateFinancialReconciliationExportTaskV2(db *gorm.DB, req *__.ExportFinancialReconciliationReq) (string, error) {
	// 3. 创建导出任务记录
	startTime := parseTime(req.StartDate)
	endTime := parseTime(req.EndDate)
	if req.UserId == "" {
		return "", errors.New("请指定操作人ID")
	}

	// 2. 检查导出记录数限制
	if req.MaxRecords > 0 {
		count, err := getFinancialReconciliationCount(db, req)
		if err != nil {
			return "", fmt.Errorf("检查导出记录数失败: %v", err)
		}
		if count > int64(req.MaxRecords) {
			return "", fmt.Errorf("导出记录数超过限制: %d > %d", count, req.MaxRecords)
		}
	}
	// 3. 创建导出任务记录
	task := &models.ExportTask{
		TaskId:       uuid.NewString(),
		UserId:       0, // 需要从req.UserId转换
		Status:       1, // 1 表示处理中
		CreatedAt:    time.Now(),
		TaskType:     2, // 2 表示财务对账导出
		ExportFormat: req.ExportFormat,
		IsEncrypted:  req.EnableEncryption,
		StartTime:    startTime,
		EndTime:      endTime,
	}

	// 转换用户ID
	if userId, err := strconv.ParseUint(req.UserId, 10, 32); err == nil {
		task.UserId = uint32(userId)
	}

	// 保存过滤参数
	filterParams, _ := json.Marshal(map[string]interface{}{
		"order_status":     req.OrderStatus,
		"payment_method":   req.PaymentMethod,
		"transaction_type": req.TransactionType,
		"filter_user_id":   req.FilterUserId,
		"filter_driver_id": req.FilterDriverId,
		"min_amount":       req.MinAmount,
		"max_amount":       req.MaxAmount,
		"order_sn":         req.OrderSn,
	})
	task.FilterParams = string(filterParams)

	// 4. 保存任务到数据库
	if err := db.Create(task).Error; err != nil {
		return "", fmt.Errorf("保存导出任务失败: %v", err)
	}

	// 5. 异步处理导出任务
	go func() {
		handleFinancialReconciliationExportV2(task.TaskId, req)
	}()

	return task.TaskId, nil
}

// getFinancialReconciliationCount 获取财务对账记录数
func getFinancialReconciliationCount(db *gorm.DB, req *__.ExportFinancialReconciliationReq) (int64, error) {
	query := db.Table("orders o").
		Joins("LEFT JOIN user u ON o.user_id = u.id").
		Joins("LEFT JOIN driver d ON o.driver_id = d.id")

	// 添加过滤条件
	if req.StartDate != "" {
		query = query.Where("o.create_at >= ?", req.StartDate)
	}
	if req.EndDate != "" {
		query = query.Where("o.create_at <= ?", req.EndDate)
	}
	if req.OrderStatus > 0 {
		query = query.Where("o.order_status = ?", req.OrderStatus)
	}
	if req.PaymentMethod > 0 {
		query = query.Where("o.pay_way = ?", req.PaymentMethod)
	}
	if req.FilterUserId != "" {
		query = query.Where("o.user_id = ?", req.FilterUserId)
	}
	if req.FilterDriverId != "" {
		query = query.Where("o.driver_id = ?", req.FilterDriverId)
	}
	if req.MinAmount > 0 {
		query = query.Where("o.price >= ?", req.MinAmount)
	}
	if req.MaxAmount > 0 {
		query = query.Where("o.price <= ?", req.MaxAmount)
	}
	if req.OrderSn != "" {
		query = query.Where("o.order_sn LIKE ?", "%"+req.OrderSn+"%")
	}

	var count int64
	err := query.Count(&count).Error
	return count, err
}

// parseTime 解析时间字符串
func parseTime(timeStr string) time.Time {
	if t, err := time.Parse("2006-01-02", timeStr); err == nil {
		return t
	}
	if t, err := time.Parse("2006-01-02 15:04:05", timeStr); err == nil {
		return t
	}
	return time.Now()
}

// handleFinancialReconciliationExportV2 处理财务对账导出V2（优化版）
func handleFinancialReconciliationExportV2(taskID string, req *__.ExportFinancialReconciliationReq) {
	// 1. 更新任务状态为处理中
	var task models.ExportTask
	if err := config.DB.Where("task_id = ?", taskID).First(&task).Error; err != nil {
		log.Printf("查询任务失败: %v", err)
		return
	}

	// 2. 查询财务对账数据
	financialData, err := getFinancialReconciliationDataForExcelV2(req)
	if err != nil {
		log.Printf("查询财务对账数据失败: %v", err)
		task.UpdateStatus(3, "查询数据失败: "+err.Error())
		return
	}

	// 3. 更新总记录数
	task.TotalCount = uint32(len(financialData))
	if err := task.UpdateStatus(1, "开始处理数据"); err != nil {
		log.Printf("更新任务状态失败: %v", err)
	}

	// 4. 根据导出格式创建文件
	var filePath string
	switch req.ExportFormat {
	case "excel":
		filePath, err = untils.CreateFinancialReconciliationExcel(taskID, financialData)
	case "csv":
		filePath, err = createFinancialReconciliationCSV(taskID, financialData)
	case "pdf":
		filePath, err = createFinancialReconciliationPDF(taskID, financialData)
	default:
		filePath, err = untils.CreateFinancialReconciliationExcel(taskID, financialData)
	}

	if err != nil {
		log.Printf("创建导出文件失败: %v", err)
		task.UpdateStatus(3, "创建文件失败: "+err.Error())
		return
	}

	// 5. 获取文件大小
	fileInfo, err := os.Stat(filePath)
	if err != nil {
		log.Printf("获取文件信息失败: %v", err)
	}

	// 6. 生成下载链接
	downloadUrl := generateDownloadUrl(taskID)

	// 7. 更新任务完成状态
	if err := task.UpdateFileInfo(filePath, fileInfo.Size(), downloadUrl); err != nil {
		log.Printf("更新任务文件信息失败: %v", err)
	}

	// 8. 如果启用加密，进行文件加密
	if req.EnableEncryption {
		encryptedPath, encryptionKey, err := encryptFile(filePath)
		if err != nil {
			log.Printf("文件加密失败: %v", err)
		} else {
			task.UpdateEncryptionInfo(true, encryptionKey)
			filePath = encryptedPath
		}
	}

	// 9. 更新任务状态为完成
	if err := task.UpdateStatus(2, "导出完成"); err != nil {
		log.Printf("更新任务状态失败: %v", err)
	}

	log.Printf("财务对账导出完成: %s", filePath)
}

// getFinancialReconciliationDataForExcelV2 获取用于Excel导出的财务对账数据V2（优化版）
func getFinancialReconciliationDataForExcelV2(req *__.ExportFinancialReconciliationReq) ([]untils.FinancialReconciliationData, error) {
	// 使用参数化查询
	query := config.DB.Table("orders o").
		Select(`
			o.order_sn AS OrderId, 
			u.id AS UserId, 
			u.nick_name AS Username, 
			d.id AS DriverId, 
			d.name AS DriverName, 
			o.create_at AS OrderTime, 
			o.start_loc AS StartLocation, 
			o.end_loc AS EndLocation, 
			o.distance AS TotalDistance, 
			o.price AS ActualPayment, 
			o.order_status AS OrderStatus, 
			o.pay_way AS PaymentMethod, 
			o.pay_time AS PaymentTime
		`).
		Joins("LEFT JOIN user u ON o.user_id = u.id").
		Joins("LEFT JOIN driver d ON o.driver_id = d.id")

	// 添加过滤条件
	if req.StartDate != "" {
		query = query.Where("o.create_at >= ?", req.StartDate)
	}
	if req.EndDate != "" {
		query = query.Where("o.create_at <= ?", req.EndDate)
	}
	if req.OrderStatus > 0 {
		query = query.Where("o.order_status = ?", req.OrderStatus)
	}
	if req.PaymentMethod > 0 {
		query = query.Where("o.pay_way = ?", req.PaymentMethod)
	}
	if req.FilterUserId != "" {
		query = query.Where("o.user_id = ?", req.FilterUserId)
	}
	if req.FilterDriverId != "" {
		query = query.Where("o.driver_id = ?", req.FilterDriverId)
	}
	if req.MinAmount > 0 {
		query = query.Where("o.price >= ?", req.MinAmount)
	}
	if req.MaxAmount > 0 {
		query = query.Where("o.price <= ?", req.MaxAmount)
	}
	if req.OrderSn != "" {
		query = query.Where("o.order_sn LIKE ?", "%"+req.OrderSn+"%")
	}

	// 执行查询
	var results []struct {
		OrderId       string  `gorm:"column:OrderId"`
		UserId        string  `gorm:"column:UserId"`
		Username      string  `gorm:"column:Username"`
		DriverId      string  `gorm:"column:DriverId"`
		DriverName    string  `gorm:"column:DriverName"`
		OrderTime     string  `gorm:"column:OrderTime"`
		StartLocation string  `gorm:"column:StartLocation"`
		EndLocation   string  `gorm:"column:EndLocation"`
		TotalDistance float64 `gorm:"column:TotalDistance"`
		ActualPayment float64 `gorm:"column:ActualPayment"`
		OrderStatus   int32   `gorm:"column:OrderStatus"`
		PaymentMethod int32   `gorm:"column:PaymentMethod"`
		PaymentTime   string  `gorm:"column:PaymentTime"`
	}

	if err := query.Order("o.create_at DESC").Scan(&results).Error; err != nil {
		return nil, fmt.Errorf("查询财务对账数据失败: %v", err)
	}

	// 转换为Excel导出格式
	var financialData []untils.FinancialReconciliationData
	for _, result := range results {
		// 计算平台费用和司机收入
		platformFee, driverIncome := calculateFees(result.ActualPayment, result.PaymentMethod)

		financialData = append(financialData, untils.FinancialReconciliationData{
			OrderId:         result.OrderId,
			UserId:          result.UserId,
			Username:        result.Username,
			DriverId:        result.DriverId,
			DriverName:      result.DriverName,
			OrderTime:       result.OrderTime,
			StartLocation:   result.StartLocation,
			EndLocation:     result.EndLocation,
			TotalDistance:   result.TotalDistance,
			ActualPayment:   result.ActualPayment,
			PlatformFee:     platformFee,
			DriverIncome:    driverIncome,
			OrderStatus:     result.OrderStatus,
			PaymentMethod:   result.PaymentMethod,
			PaymentTime:     result.PaymentTime,
			CouponDiscount:  0,
			SurgeMultiplier: 1.0,
			Remark:          "",
		})
	}

	return financialData, nil
}

// createFinancialReconciliationCSV 创建CSV文件
func createFinancialReconciliationCSV(taskID string, data []untils.FinancialReconciliationData) (string, error) {
	// 实现CSV导出逻辑
	return "", nil
}

// createFinancialReconciliationPDF 创建PDF文件
func createFinancialReconciliationPDF(taskID string, data []untils.FinancialReconciliationData) (string, error) {
	// 实现PDF导出逻辑
	return "", nil
}

// generateDownloadUrl 生成下载链接
func generateDownloadUrl(taskID string) string {
	// 实现下载链接生成逻辑
	return fmt.Sprintf("/api/v1/export/download/%s", taskID)
}

// encryptFile 加密文件
func encryptFile(filePath string) (string, string, error) {
	// 实现文件加密逻辑
	return filePath, "", nil
}
